/**
 * 
 */
package cn.ad.server.web.servlet.v2.requesthandler;

import cn.ad.server.web.log.IAdEventLogger;
import cn.ad.server.web.log.entity.AdserverEventLog;
import cn.ad.server.web.spring.service.actions.IAdRequestAction;
import cn.ad.server.web.spring.service.actions.command.AdCallBackRequest;
import cn.ad.server.web.utils.HttpUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 第三方监测。激活回调。
 * @author wangwei 
 *
 */
@Deprecated
public class ActivationCallBackHandler extends AbstractRequestHandler{
	
	/**
	 * 
	 */
	private static Logger LOGGER = LoggerFactory.getLogger(ActivationCallBackHandler.class);
	/**
	 * guid
	 */
	private static final String PARAM_GUID = "guid";

	/**
	 * 素材id
	 */
	private static final String PARAM_MID = "mid";

	/**
	 * 创意id
	 */
	private static final String PARAM_CID = "cid";

	/**
	 * 策略id
	 */
	private static final String PARAM_SID = "sid";

	/**
	 * 广告位id
	 */
	private static final String PARAM_AID = "aid";

	/**
	 * 设备-androidid_md5
	 */
	private static final String PARAM_ANDROIDID_MD5 = "androidid_md5";

	/**
	 * 设备-androidid
	 */
	private static final String PARAM_ANDROIDID = "androidid";

	/**
	 * 设备-imei_md5
	 */
	private static final String PARAM_IMEI_MD5 = "imei_md5";

	/**
	 * 设备-imei
	 */
	private static final String PARAM_IMEI = "imei";

	/**
	 * 设备-idfa_md5
	 */
	private static final String PARAM_IDFA_MD5 = "idfa_md5";

	/**
	 * 设备-idfa
	 */
	private static final String PARAM_IDFA = "idfa";

	/**
	 * 设备-mac_md5
	 */
	private static final String PARAM_MAC_MD5 = "mac_md5";

	/**
	 * 设备-mac
	 */
	private static final String PARAM_MAC = "mac";

	/**
	 * 设备-系统
	 */
	private static final String PARAM_OS = "os";

	
	/**
	 * 渠道参数名称，用于在路径获取请求字符串标识渠道的参数名称
	 */
	private static final String CHANNEL_PARAM_NAME = "ch";
	
	/**
	 * Adserver 日志记录实现接口
	 */
	private IAdEventLogger adEventLogger;

	/**
	 * RequestAction 接口
	 */
	private IAdRequestAction requestAction;
	
	/**
	 * 构造函数
	 */
	public ActivationCallBackHandler() {
		super();
	}
	
	/*
	 * (non-Javadoc)
	 * @see cn.ad.server.web.servlet.v2.AdserverGenericServlet#doService(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	@Override
	public void handle(HttpServletRequest request, HttpServletResponse response) throws RequestHandleException{
		doService(request, response);
		
	}

	/**
	 * 业务处理。
	 * @param request
	 * @param response
	 */
	void doService(HttpServletRequest request, HttpServletResponse response) {
		LOGGER.debug("AdTrackServlet doService 开始");
		try {
			AdCallBackRequest trackCommand = new AdCallBackRequest();
			convetGetRequestParam(request, trackCommand);
			
			LOGGER.info("talkingback请求Url: "+request.getRequestURI()+"\n"+"talkingback 回传信息: "+trackCommand.toString());
			
			response.setStatus(200);
			response.setHeader("Connection", "close");
			
			if(isNeedRetransmission(trackCommand)){				
				IAdRequestAction action = getRequestAction();
				if(action!=null){
					action.doRequest(trackCommand);
				}
			}

		} catch (Exception e) {
			LOGGER.error("//v2/talkingdata/ch/4 error", e);
			response.setStatus(501);
			response.setHeader("Connection", "close");
		} finally {
			LOGGER.debug("AdTrackServlet doService 结束");
			//loggerService.logAdClick(cp); TODO do....
		}
	}
	
	/**
	 * 是否需要转发给第三方补量渠道。
	 * 判断是正常click还是第三方补量返回的激活。
	 * 依据：
	 * cid=（0或‘’）且sid=（0或‘’）
	 * 
	 * TODO mid=（0或‘’）是否判断。当如果是原生情况下mid为0.
	 * 
	 * @param trackCommand
	 * @return
	 */
	boolean isNeedRetransmission(AdCallBackRequest trackCommand){
		if(isZeroEmpty(trackCommand.getCid())&&isZeroEmpty(trackCommand.getSid())){//TODO trackCommand.getMid()>0 是否加。
			return true;
		}else{
			return false;
		}
	}
	
	/**
	 * 判断是否是空或0
	 * @param src
	 * @return
	 */
	boolean isZeroEmpty(String src){
		if("0".equals(src)||"".equals(src)){
			return true;
		}
		return false;
	}

	

	/**
	 * 获取请求来源接入渠道平台
	 * @param request
	 * @return
	 */
	protected String getChannel(HttpServletRequest request){
		return getChannelFromUriPath(request);
	}
	
	
	/**
	 * 从请求路径中获取渠道标识
	 * @param request
	 * @return
	 */
	private String getChannelFromUriPath(HttpServletRequest request){
		String ch = HttpUtils.getPathParam(request.getServletPath(), CHANNEL_PARAM_NAME);
		return ch;
	}

	/**
	 * @return the adEventLogger
	 */
	public IAdEventLogger getAdEventLogger() {
		return adEventLogger;
	}

	/**
	 * @param adEventLogger the adEventLogger to set
	 */
	public void setAdEventLogger(IAdEventLogger adEventLogger) {
		this.adEventLogger = adEventLogger;
	}

	/**
	 * 记录广告事件日志
	 * @param eventlog
	 */
	protected void logAdserverEventLog(AdserverEventLog eventlog){
		adEventLogger.log(eventlog);
	}


	/**
	 * @return the requestAction
	 */
	public IAdRequestAction getRequestAction() {
		return requestAction;
	}


	/**
	 * @param requestAction the requestAction to set
	 */
	public void setRequestAction(IAdRequestAction requestAction) {
		this.requestAction = requestAction;
	}
	
	/**
	 * 获取请求参数填充AdCallBackRequest对象。
	 * 
	 */
	private void convetGetRequestParam(HttpServletRequest request, AdCallBackRequest trackCommand) {
		String os = request.getParameter(PARAM_OS);
		trackCommand.setOs(null2Empty(os));
		
		String mac = request.getParameter(PARAM_MAC);
		trackCommand.setMac(null2Empty(mac));
		
		String mac_md5 = request.getParameter(PARAM_MAC_MD5);
		trackCommand.setMac_md5(null2Empty(mac_md5));
		
		String idfa = request.getParameter(PARAM_IDFA);
		trackCommand.setIdfa(null2Empty(idfa));
		
		String idfa_md5 = request.getParameter(PARAM_IDFA_MD5);
		trackCommand.setIdfa_md5(null2Empty(idfa_md5));
		
		String imei = request.getParameter(PARAM_IMEI);
		trackCommand.setImei(null2Empty(imei));
		
		String imei_md5 = request.getParameter(PARAM_IMEI_MD5);
		trackCommand.setImei_md5(null2Empty(imei_md5));
		
		String androidid = request.getParameter(PARAM_ANDROIDID);
		trackCommand.setAndroidid(null2Empty(androidid));
		
		String androidid_md5 = request.getParameter(PARAM_ANDROIDID_MD5);
		trackCommand.setAndroidid_md5(null2Empty(androidid_md5));
		
		//以上必定一个
		
		String aid = request.getParameter(PARAM_AID);
		trackCommand.setAid(null2Empty(aid));
		
		String sid = request.getParameter(PARAM_SID);
		trackCommand.setSid(null2Empty(sid));
		
		String cid = request.getParameter(PARAM_CID);
		trackCommand.setCid(null2Empty(cid));
		
		String mid = request.getParameter(PARAM_MID);
		trackCommand.setMid(null2Empty(mid));
		
		String guid = request.getParameter(PARAM_GUID);
		trackCommand.setGuid(null2Empty(guid));
		
		String ch = getChannelFromUriPath(request);
		
		trackCommand.setCh(null2Empty(ch));
		
		trackCommand.setChannelID(getChannelFromUriPath(request));
	}
	
	/**
	 * 如果null返回 空字符
	 * @param os
	 * @return
	 */
	private String null2Empty(String os){
		if(os==null){
			os="";
		}
		return os;
	}
}
